#include<stdio.h>
#include<stdlib.h>

#include "mysql.h"

int main(void)
{
	MYSQL myConnection;
	int res;
	MYSQL* pConnPtr;

	mysql_init(&myConnection);

	pConnPtr = mysql_real_connect(&myConnection, "localhost", "root", "123456", "rick", 0, NULL, 0);
	if (NULL == pConnPtr)
	{
		printf("Connection failed\n");
		if (mysql_errno(&myConnection))
		{
			fprintf(stderr, "Connection error %d: %s\n",
			mysql_errno(&myConnection), mysql_error(&myConnection));
		}

		return EXIT_FAILURE;
	}

	res = mysql_query(&myConnection, "CREATE TABLE children( \
			childno int(11) AUTO_INCREMENT NOT NULL PRIMARY KEY, \
			fname varchar(30), \
			age int \
			);"
			);
	if (0 == res)
	{
		printf ("Create table success: %lu.\n", (unsigned long)mysql_affected_rows(&myConnection));
	}
	else
	{
		fprintf(stderr, "Create table failed %d : %s\n", mysql_errno(&myConnection), mysql_error(&myConnection));
	}

	res = mysql_query(&myConnection, "INSERT INTO children(fname, age) VALUES('Ann', 3)");
	res = mysql_query(&myConnection, "INSERT INTO children(fname, age) VALUES('Ann', 4)");
	if (0 == res)
	{
		printf ("Insert into table success: %lu.\n", (unsigned long)mysql_affected_rows(&myConnection));
	}

	res = mysql_query(&myConnection, "UPDATE children SET age = age + 1 WHERE fname = 'Ann'");
	if (0 == res)
	{
		printf ("update table success: %lu.\n", (unsigned long)mysql_affected_rows(&myConnection));
	}
	else
	{
		fprintf(stderr, "Create table failed %d : %s\n", mysql_errno(&myConnection), mysql_error(&myConnection));
	}

	res = mysql_query(&myConnection, "SELECT LAST_INSERT_ID()");
	if (0 == res)
	{
		MYSQL_RES* resPtr;
		MYSQL_ROW sqlRow;
		resPtr = mysql_use_result(&myConnection);
		if (NULL != resPtr)
		{
			while ((sqlRow = mysql_fetch_row(resPtr)))
			{
				printf("We inserted childno %s\n", sqlRow[0]);
			}
		}
		mysql_free_result(resPtr);
	}
	else
	{
		printf("SELECT error: %s\n", mysql_error(&myConnection));
	}

	res = mysql_query(&myConnection, "SELECT childno, fname, age FROM children WHERE age > 5");
	if (0 == res)
	{
		MYSQL_RES* resPtr;
		MYSQL_ROW sqlRow;
		resPtr = mysql_use_result(&myConnection);
		if (NULL != resPtr)
		{
			int fieldCount;
			fieldCount = mysql_field_count(&myConnection);

			while ((sqlRow = mysql_fetch_row(resPtr)))
			{
				int i = 0;

				printf("Fetched data: ");
				for (i = 0; i < fieldCount; i++)
				{
					printf("%s ", sqlRow[i]);
				}
				printf("\n");\
			}
		}
		mysql_free_result(resPtr);
	}
	else
	{
		printf("SELECT error: %s\n", mysql_error(&myConnection));
	}

	mysql_close(&myConnection);

	return EXIT_SUCCESS;
}

